
STLOGGERTITLE = "afterSubmit_autoCreateProjectandWO";
DEBUG = true;
function afterSubmit_autoCreateProjectandWO(type)
{
	try
	{
		logger("*Entry log*");
		
		if(type != "approve") 
		{
			logger("Type is: " + type + ". Terminate script.");
			return;
		}
		var recSO = nlapiLoadRecord(nlapiGetRecordType(), nlapiGetRecordId());
		var recProj = nlapiCreateRecord("job", {recordmode: 'dynamic'});	
		
		recProj.setFieldValue("subsidiary", recSO.getFieldValue("subsidiary"));
		
		recProj.setFieldValue("parent", recSO.getFieldValue("entity"));
		var stIdProj = nlapiSubmitRecord(recProj, true, true);
		
		logger("Successfully created job (id) " + stIdProj);

		for(var x = 1; x <= recSO.getLineItemCount("item"); x++)
		{
			recSO.selectLineItem("item", x);
			recSO.setCurrentLineItemValue("item", "job", stIdProj);
			recSO.commitLineItem("item");
		}
		
		var strSOID = nlapiSubmitRecord(recSO);
		logger("Successfully updated sales order (id) " + strSOID);

		//Create work order
		createWorkOrder(recSO, stIdProj);
		
		var stQuoteId = recSO.getFieldValue('createdfrom');
		
		if(!stQuoteId){
			logger("No Quote Id");
			return;
		}
		
		var recQuote = nlapiLoadRecord('estimate', stQuoteId);

		for(var x = 1; x <= recQuote.getLineItemCount("item"); x++)
		{
			recQuote.selectLineItem("item", x);
			recQuote.setCurrentLineItemValue("item", "job", stIdProj);
			recQuote.commitLineItem("item");
		} 
		
		nlapiSubmitRecord(recQuote);
		logger("Successfully updated quote (id) " + strSOID);
		
		logger("*End of script*");

	}catch(error)
	{
		if (error.getDetails != undefined) 
	   {
		   nlapiLogExecution('ERROR', 'Process Error', error.getCode() + ': ' + error.getDetails());
		   throw error;
	   }
	   else 
	   {    
		   nlapiLogExecution('ERROR', 'Unexpected Error', error.toString());
		   throw nlapiCreateError('99999', error.toString());
	   }
	}

}

//Create a work order based on the SO details
function  createWorkOrder(recSO, recProj){

	var ST_LOG_TITLE = "Creating a workorder";
	logger(ST_LOG_TITLE);
	//Getters
	var stCustomer   = recSO.getFieldValue("entity");
	var stSubsidiary = recSO.getFieldValue("subsidiary");
	var stLocation   = recSO.getFieldValue("location");
	var stClass      = recSO.getFieldValue("class");
	var stDepartment = recSO.getFieldValue("department");
	var stPromDate   = recSO.getFieldValue("custbody_promisedate");
	
	var qbomRecType = "recmachcustrecord_tti_sales_order";
	var stQBOMId = recSO.getLineItemValue(qbomRecType, "custrecord_tti_item", 1);
	
	var stAssemblyItem = nlapiLookupField('customrecord_tti_rfqbom', stQBOMId, 'custrecord_assembly_item');
	
	nlapiLogExecution('DEBUG',ST_LOG_TITLE, 
					'stCustomer 	= ' +  stCustomer
		+ '\n <br /> stSubsidiary   = ' +  stSubsidiary
		+ '\n <br /> stLocation		= ' +  stLocation
		+ '\n <br /> stClass		= ' +  stClass
		+ '\n <br /> stDepartment	= ' +  stDepartment
		+ '\n <br /> stPromDate		= ' +  stPromDate
		+ '\n <br /> stAssemblyItem	= ' +  stAssemblyItem
	);
	
	var recWorkOrder = nlapiCreateRecord("workorder", {recordmode: 'dynamic'});
	recWorkOrder.setFieldValue("subsidiary", stSubsidiary);
	recWorkOrder.setFieldValue("entity", stCustomer);
	recWorkOrder.setFieldValue("assemblyitem", stAssemblyItem); 
	recWorkOrder.setFieldValue("location", stLocation);
	recWorkOrder.setFieldValue("class", stClass);
	recWorkOrder.setFieldValue("department", stDepartment);
	recWorkOrder.setFieldValue("custbody_promisedate", stPromDate);
	recWorkOrder.setFieldValue("custbody21", recProj);
	
	var intQbomItemCount = recSO.getLineItemCount(qbomRecType);
	
	var isUpdated = false;
	var objItem = new Object ();
	
	for (var i = 0; i < intQbomItemCount; i++)
	{
		var j = i+1;
		var stQbomItemName = recSO.getLineItemValue(qbomRecType, "custrecord_tti_itemname", j);
		var stQbomQty      = recSO.getLineItemValue(qbomRecType, "custrecord_tti_quantity", j);
		var stAvePrice     = recSO.getLineItemValue(qbomRecType, "custrecord_tti_aveprice", j);
		var stLastPurPrice = recSO.getLineItemValue(qbomRecType, "custrecord_tti_lastpurchaseprice", j);
		var stLastPurDate  = recSO.getLineItemValue(qbomRecType, "custrecord_tti_last_purchase_date", j);
		var stHighestPrice = recSO.getLineItemValue(qbomRecType, "custrecord_tti_highestprice", j);
		var stLowestPrice  = recSO.getLineItemValue(qbomRecType, "custrecord_tti_lowestpurchaseprice", j);
		var stPrefPrice    = recSO.getLineItemValue(qbomRecType, "custrecord_tti_prefprice", j);
		var stFinalLocCurr = recSO.getLineItemValue(qbomRecType, "custrecord_tti_finalpricelocal", j);
		var stFinalForCurr = recSO.getLineItemValue(qbomRecType, "custrecord_tti_finalpriceforeign", j);
		

		objItem[stQbomItemName] = {};
		objItem[stQbomItemName].name     		= stQbomQty;
		objItem[stQbomItemName].aveprice 		= stAvePrice;
		objItem[stQbomItemName].lastpurprice 	= stLastPurPrice;
		objItem[stQbomItemName].lastpurdate 	= stLastPurDate;
		objItem[stQbomItemName].highesprice 	= stHighestPrice;
		objItem[stQbomItemName].lowestprice 	= stLowestPrice;
		objItem[stQbomItemName].prefprice 		= stPrefPrice;
		objItem[stQbomItemName].finalloccurr 	= stFinalLocCurr;
		objItem[stQbomItemName].finalforcurr 	= stFinalForCurr;
		
		
		nlapiLogExecution('DEBUG',ST_LOG_TITLE, 
						'stQbomItemName 	= ' +  stQbomItemName
			+ '\n <br /> stQbomQty   		= ' +  stQbomQty
			+ '\n <br /> stAvePrice   		= ' +  stAvePrice
			+ '\n <br /> stLastPurPrice   	= ' +  stLastPurPrice
			+ '\n <br /> stLastPurDate   	= ' +  stLastPurDate
			+ '\n <br /> stHighestPrice   	= ' +  stHighestPrice
			+ '\n <br /> stLowestPrice   	= ' +  stLowestPrice
			+ '\n <br /> stPrefPrice   		= ' +  stPrefPrice
			+ '\n <br /> stFinalLocCurr   	= ' +  stFinalLocCurr
			+ '\n <br /> stFinalForCurr   	= ' +  stFinalForCurr
		);

	}
	
	var intWOItemCount = recWorkOrder.getLineItemCount('item');
	
	for (var i = 0; i < intWOItemCount; i++)
	{
		var j = i+1;
		var stWOItemName  =  recWorkOrder.getLineItemValue('item', "item", j);
		
		nlapiLogExecution('DEBUG',ST_LOG_TITLE, 
			'stWOItemName 	= ' +  stWOItemName
			+ '\n <br /> objItem[stWOItemName]' + objItem[stWOItemName]
		);
		
		if(objItem[stWOItemName])
		{
			recWorkOrder.setLineItemValue('item', 'quantity'			 		   , j,  objItem[stWOItemName].name);
			recWorkOrder.setLineItemValue('item', 'custcol_tti_aveprice'           , j,  objItem[stWOItemName].aveprice);
			recWorkOrder.setLineItemValue('item', 'custcol_tti_lastpurchaseprice'  , j,  objItem[stWOItemName].lastpurprice);
			recWorkOrder.setLineItemValue('item', 'custcol_tti_lastpurchasedate'   , j,  objItem[stWOItemName].lastpurdate);
			recWorkOrder.setLineItemValue('item', 'custcol_tti_highestprice'       , j,  objItem[stWOItemName].highesprice);
			recWorkOrder.setLineItemValue('item', 'custcol_tti_lowestpurchaseprice', j,  objItem[stWOItemName].lowestprice);
			recWorkOrder.setLineItemValue('item', 'custcol_tti_prefprice'          , j,  objItem[stWOItemName].prefprice);
			recWorkOrder.setLineItemValue('item', 'custcol_tti_finallocalcurr'     , j,  objItem[stWOItemName].finalloccurr);
			recWorkOrder.setLineItemValue('item', 'custcol_tti_finalforeigncurr'   , j,  objItem[stWOItemName].finalforcurr);
			isUpdated = true;
		}
		
	};
	
	if(isUpdated)
	{
		var stWorkOrderId = nlapiSubmitRecord(recWorkOrder);
		logger("Successfully created WO (id) " + stWorkOrderId);
	} else 
	{
		logger("No line item to update");
	}
	
}

function logger(details) 
{
	if(DEBUG === true)
	{
		nlapiLogExecution("DEBUG", STLOGGERTITLE, details);
	}
}